import 'dart:async';
import 'dart:convert';
import 'dart:ui';
import 'package:flutter/material.dart';
import 'package:flutter_rider/generated/assets.dart';
import 'package:flutter_rider/main/widgets/base/detail_flexStart_layout.dart';
import 'package:flutter_rider/main/widgets/base/detail_flexStart_undeline_layout.dart';
import 'package:flutter_rider/main/widgets/base/kv_layout.dart';
import 'package:flutter_rider/main/widgets/ext/u_layout.dart';
import 'package:flutter_rider/main/widgets/ext/u_text.dart';
import 'package:flutter_rider/main/widgets/ext/u_title_layout.dart';
import 'package:flutter_rider/main/widgets/state/state_layout.dart';
import 'package:flutter_rider/module/task/page/task_list_page.dart';
import 'package:flutter_rider/module/waybill/page/copy_order_page.dart';
import 'package:flutter_rider/module/waybill/waybill_router.dart';
import 'package:flutter_rider/routers/fluro_navigator.dart';
import 'package:flutter_rider/utils/open_utils.dart';
import 'package:flutter_rider/utils/screen_fit.dart';
import 'package:flutter_rider/main/widgets/ui_constant.dart';
import 'package:flutter_rider/utils/log.dart';
import 'package:flutter_rider/event/refresh_order_event.dart';
import 'package:flutter_rider/main.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../../../utils/tip.dart';

class WaybillDetailPage extends StatefulWidget {
  String id;
  WaybillDetailPage(this.id, {Key? key}) : super(key: key);

  @override
  State createState() => OrderDetailPageState();
}

class OrderDetailPageState extends State<WaybillDetailPage> {
  dynamic _data;
  final StateLayoutController _stateLayoutController = StateLayoutController();
  late StreamSubscription _eventFn;
  @override
  void initState() {
    super.initState();
    _eventFn = eventBus.on<RefreshOrderEvent>().listen((event) {
      _stateLayoutController.reload();
    });
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    _eventFn.cancel();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: UIColor.color_main,
      appBar: UTitleLayout.getBackTitle(context, "运单详情"),
      body: StateLayout(
        url: "/waybill/detail?waybill_no=${widget.id}",
        controller: _stateLayoutController,
        childBuilder: _renderContent,
        dataCallback: (data) {
          _data = data;
        },
      ).padding(EdgeInsets.only(
          left: MediaQuery.of(context).padding.left,
          right: MediaQuery.of(context).padding.right)),
    );
  }

  Widget _renderContent(dynamic data) {
    return Column(
      children: [
        Expanded(
          child: SingleChildScrollView(
            child: Column(
              children: [
                _noAndShop(),
                10.hspace,
                _task(),
                10.hspace,
                _deliverInfo(),
                10.hspace,
                _consigneeInfo(),
                10.hspace,
                _goodInfo(),
                30.hspace,
              ],
            ),
          ),
        ),
        data["is_ka"] == 1
            ? Padding(
                padding: EdgeInsets.all(12.rpx),
                child: UText.getBkButton("复制运单", 16.rpx,
                    bkColor: UIColor.color_primary,
                    radius: 12.rpx,
                    width: double.infinity,
                    height: 48.rpx, onPressed: () async {
                  var _sp = await SharedPreferences.getInstance();
                  bool _showCopyWaybillOrder =
                      _sp.getBool("_showCopyWaybillOrder") as bool;
                  if (_showCopyWaybillOrder) {
                    OpenUtils.open(context, CopyOrderPage(_data));
                  } else {
                    Tip.show("当前没有“复制运单”的权限，无法操作");
                  }
                }),
              )
            : 0.wspace,
        SizedBox(height: MediaQuery.of(context).padding.bottom),
      ],
    );
  }

  Widget _noAndShop() {
    var st = _data["status"];
    dynamic widget, bgColor, color, name;
    if (st == 1) {
      bgColor = const Color(0xffED7B2F);
      color = UIColor.color_content;
      name = "待确认";
    } else if (st == 2) {
      bgColor = const Color(0xff00A870);
      color = UIColor.color_content;
      name = "履约中";
    } else if (st == 3) {
      bgColor = UIColor.color_input;
      color = UIColor.color_t9;
      name = "已完成";
    } else if (st == -1) {
      bgColor = UIColor.color_input;
      color = UIColor.color_t7;
      name = "已取消";
    } else {
      return widget = 0.wspace;
    }
    widget = Container(
      width: 66.rpx,
      height: 32.rpx,
      alignment: Alignment.center,
      decoration: BoxDecoration(
        color: bgColor,
        borderRadius: const BorderRadius.only(
            topLeft: Radius.circular(60), bottomLeft: Radius.circular(60)),
      ),
      child: UText.get(name, color, 14.rpx),
    );
    return Container(
        padding: EdgeInsets.only(left: 16.rpx),
        decoration: const BoxDecoration(
          color: UIColor.color_content,
        ),
        child: Column(children: [
          Container(
              padding: EdgeInsets.only(top: 12.rpx, bottom: 0.rpx),
              child: Row(
                children: [
                  UText.get("运单编号", UIColor.color_t7, 16.rpx),
                  16.wspace,
                  UText.get(_data["waybill_no"], UIColor.color_t1, 16.rpx)
                      .expand,
                  Container(
                    width: 66.rpx,
                    height: 32.rpx,
                    alignment: Alignment.center,
                    decoration: BoxDecoration(
                      color: UIColor.color_t6,
                      borderRadius: const BorderRadius.only(
                          topLeft: Radius.circular(60),
                          bottomLeft: Radius.circular(60)),
                    ),
                    child: widget,
                  )
                ],
              )),
          Container(
              padding: EdgeInsets.only(top: 6.rpx, bottom: 12.rpx),
              child: Row(
                children: [
                  UText.get("店铺名称", UIColor.color_t7, 16.rpx),
                  16.wspace,
                  UText.get(_data["merchant_name"], UIColor.color_t1, 16.rpx),
                ],
              )),
          2.hspace,
        ]));
  }

  Widget _task() {
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      child: Container(
        height: 48.rpx,
        padding: EdgeInsets.symmetric(horizontal: 16.rpx),
        decoration: const BoxDecoration(
          color: UIColor.color_content,
        ),
        child: Row(
          children: [
            UText.get("任务数量", UIColor.color_t7, 16.rpx),
            16.wspace,
            UText.get("X" + _data["mission_num"].toString(), UIColor.color_t1,
                16.rpx),
            const Spacer(),
            Icon(Icons.navigate_next, size: 20.rpx, color: UIColor.color_t3),
          ],
        ),
      ),
      onTap: () {
        OpenUtils.open(
            context,
            TaskListPage(
                _data["status"], _data["waybill_no"], _data["is_ka"].toInt()));
      },
    );
  }

  Widget _deliverInfo() {
    return Container(
      decoration: const BoxDecoration(
        color: UIColor.color_content,
      ),
      child: Column(
        children: [
          Container(
            padding: EdgeInsets.only(
                left: 16.rpx, top: 16.rpx, right: 16.rpx, bottom: 12.rpx),
            alignment: Alignment.centerLeft,
            child: UText.get("发货信息", UIColor.color_t5, 14.rpx,
                fw: FontWeight.w600, textAlign: TextAlign.left),
          ),
          Container(height: 0.5.rpx, color: UIColor.color_divider),
          12.hspace,
          DetailFlexStartLayout('发货人', _data["pick_username"]),
          12.hspace,
          DetailFlexStartUndelineLayout('发货电话', _data["pick_tel"]),
          12.hspace,
          DetailFlexStartLayout('发货地址', _data["pick_address"]),
          12.hspace,
          DetailFlexStartLayout('详细描述', _data["pick_addr_desc"]),
          12.hspace,
          DetailFlexStartLayout('发货车牌', _data["pick_car_plate"]),
          12.hspace,
        ],
      ),
    );
  }

  Widget _consigneeInfo() {
    return Container(
      decoration: const BoxDecoration(
        color: UIColor.color_content,
      ),
      child: Column(
        children: [
          Container(
            padding: EdgeInsets.only(
                left: 16.rpx, top: 16.rpx, right: 16.rpx, bottom: 12.rpx),
            alignment: Alignment.centerLeft,
            child: UText.get("收货信息", UIColor.color_t5, 14.rpx,
                fw: FontWeight.w600, textAlign: TextAlign.left),
          ),
          Container(height: 0.5.rpx, color: UIColor.color_divider),
          12.hspace,
          DetailFlexStartLayout('收货人', _data["delivery_username"]),
          12.hspace,
          DetailFlexStartUndelineLayout('收货电话', _data["delivery_tel"]),
          12.hspace,
          DetailFlexStartLayout('收货地址', _data["delivery_address"]),
          12.hspace,
          DetailFlexStartLayout('详细描述', _data["delivery_addr_desc"]),
          12.hspace,
          DetailFlexStartLayout('收货车牌', _data["delivery_car_plate"]),
          12.hspace,
        ],
      ),
    );
  }

  Widget _goodInfo() {
    List<dynamic> jSku = [];
    try {
      jSku = jsonDecode(_data["sku_option"]);
      Log.i("jSku", jSku);
    } catch (e, st) {
      Log.i("", e, st);
    }
    var isModifi = _data["editable"];
    
    return Container(
      decoration: const BoxDecoration(
        color: UIColor.color_content,
      ),
      child: Column(
        children: [
          Row(
            children: [
              Container(
                padding: EdgeInsets.only(
                    left: 16.rpx, top: 16.rpx, right: 8.rpx, bottom: 12.rpx),
                alignment: Alignment.centerLeft,
                child: UText.get("货物信息", UIColor.color_primary, 14.rpx,
                    fw: FontWeight.w600, textAlign: TextAlign.left),
              ),
              Visibility(
                  visible: _data["modified"],
                  child: SvgPicture.asset(Assets.imageWaybillUpdate,
                      width: 46.rpx, height: 20.rpx)),
              const Spacer(),
              UText.get(
                  "去修改",
                  isModifi ? UIColor.color_primary : UIColor.color_disable,
                  14.rpx),
              16.wspace
            ],
          ).onTap(() {
            if (isModifi) {
              NavigatorUtils.push(context, WaybillRouter.waybillChangePage,
                  arguments: _data);
            }
          }),
          Container(height: 0.5.rpx, color: UIColor.color_divider),
          12.hspace,
          KvLayout("货物类别", _data["spu_product_name"].toString()),
          ...jSku
              .asMap()
              .values
              .map((e) => KvLayout(e["name"], e["val"])
                  .padding(EdgeInsets.only(top: 10.rpx)))
              .toList(),
          _renderAmount(),
          12.hspace,
          KvLayout("件数(件)", _data["qty"].toString()),
          12.hspace,
        ],
      ),
    );
  }

  Widget _renderAmount() {
    return Container(
        child: _data["unit"] == 2
            ? Column(
                children: [
                  12.hspace,
                  KvLayout("数量（吨）", (_data["total_weight"] / 1000.0).toString())
                ],
              )
            : 0.wspace);
  }

  _onClickSubmit() {}
}
